package util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

public class SerializationHelper<E> {
	
	public void Serialize(Object o, File f) {
		FileOutputStream fs = null;
		try {
			fs = new FileOutputStream(f);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		
		Serialize(o, fs);
	}
	
	public void Serialize(Object o, OutputStream stream) {
		try {
			ObjectOutputStream os = new ObjectOutputStream(stream);
			os.writeObject(o);
			os.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public ByteArrayInputStream toByteInputStream(Object o) {
		ByteArrayOutputStream bs = new ByteArrayOutputStream();
		try {			 
			ObjectOutputStream os = new ObjectOutputStream(bs);
			os.writeObject(o);
			os.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return new ByteArrayInputStream(bs.toByteArray());
	}
	
	public E Deserialize(File f) {
		FileInputStream fs = null;
		try {
			fs = new FileInputStream(f);
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} 
		

		ObjectInputStream os;
		Object cf = null;
		try {
			os = new ObjectInputStream(fs);
			cf = os.readObject();
			os.close();
		}catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		
		return (E)cf;
	}

}
